package com.atguigu.gmall.realtime.dwd.db.split.function;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.bean.TableProcessDwd;
import com.atguigu.gmall.realtime.common.util.JdbcUtil;
import org.apache.flink.api.common.state.BroadcastState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReadOnlyBroadcastState;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.co.BroadcastProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Connection;
import java.util.*;

/**
 * @author Felix
 * @date 2024/7/31
 * 对关联后的数据进行处理(过滤出处理逻辑比较简单的事实表数据)
 */
public class BaseDbTableProcessFunction extends BroadcastProcessFunction<JSONObject, TableProcessDwd, Tuple2<JSONObject,TableProcessDwd>>{

    private MapStateDescriptor<String, TableProcessDwd> mapStateDescriptor;

    private Map<String,TableProcessDwd> configMap = new HashMap<>();

    public BaseDbTableProcessFunction(MapStateDescriptor<String, TableProcessDwd> mapStateDescriptor) {
        this.mapStateDescriptor = mapStateDescriptor;
    }

    //将配置表的信息预加载到程序中
    @Override
    public void open(Configuration parameters) throws Exception {
        Connection conn = JdbcUtil.getMysqlConnection();
        String sql = "select * from gmall0221_config.table_process_dwd";
        List<TableProcessDwd> tableProcessDwdList = JdbcUtil.queryList(conn, sql, TableProcessDwd.class, true);
        for (TableProcessDwd tableProcessDwd : tableProcessDwdList) {
            String sourceTable = tableProcessDwd.getSourceTable();
            String sourceType = tableProcessDwd.getSourceType();
            String key = getKey(sourceTable, sourceType);
            configMap.put(key,tableProcessDwd);
        }
        JdbcUtil.closeConnection(conn);

    }

    //拼接key
    private static String getKey(String sourceTable, String sourceType) {
        String key = sourceTable + ":" + sourceType;
        return key;
    }

    //处理主流业务数据
    @Override
    public void processElement(JSONObject jsonObj, BroadcastProcessFunction<JSONObject, TableProcessDwd, Tuple2<JSONObject, TableProcessDwd>>.ReadOnlyContext ctx, Collector<Tuple2<JSONObject, TableProcessDwd>> out) throws Exception {
        //获取业务数据库表的表名
        String table = jsonObj.getString("table");
        //获取业务数据库表的操作类型
        String type = jsonObj.getString("type");
        //拼接key
        String key = getKey(table, type);
        //获取广播状态
        ReadOnlyBroadcastState<String, TableProcessDwd> broadcastState = ctx.getBroadcastState(mapStateDescriptor);

        //根据上述拼接的key，到广播状态以及ConfigMap中去找对应的配置信息，如果找到了，说明是处理逻辑比较简单的事实表数据
        TableProcessDwd tableProcessDwd = null;

        if((tableProcessDwd =  broadcastState.get(key)) != null
           ||(tableProcessDwd =  configMap.get(key)) != null){
            //只需要将data部分内容获取发送到kafka主题即可
            JSONObject dataJsonObj = jsonObj.getJSONObject("data");
            //在向下游传递数据前，过滤掉不需要传递的属性
            String sinkColumns = tableProcessDwd.getSinkColumns();
            deleteNotNeedColumn(dataJsonObj,sinkColumns);
            //在向下游传递数据前，补充ts属性
            Long ts = jsonObj.getLong("ts");
            dataJsonObj.put("ts",ts);
            out.collect(Tuple2.of(dataJsonObj,tableProcessDwd));
        }

    }

    //过滤掉不需要传递的字段
    private void deleteNotNeedColumn(JSONObject dataJsonObj, String sinkColumns) {
        List<String> columnList = Arrays.asList(sinkColumns.split(","));
        Set<Map.Entry<String, Object>> entrySet = dataJsonObj.entrySet();
        entrySet.removeIf(entry-> !columnList.contains(entry.getKey()));
    }

    //处理广播流配置信息
    @Override
    public void processBroadcastElement(TableProcessDwd tp, BroadcastProcessFunction<JSONObject, TableProcessDwd, Tuple2<JSONObject, TableProcessDwd>>.Context ctx, Collector<Tuple2<JSONObject, TableProcessDwd>> out) throws Exception {
        //获取对配置表进行操作的类型
        String op = tp.getOp();
        //获取广播状态
        BroadcastState<String, TableProcessDwd> broadcastState = ctx.getBroadcastState(mapStateDescriptor);
        //拼接key
        String sourceTable = tp.getSourceTable();
        String sourceType = tp.getSourceType();
        String key = getKey(sourceTable, sourceType);
        if("d".equals(op)){
            //从配置表中删除了一条配置信息  同时应该从状态以及ConfigMap中删除对应的配置
            broadcastState.remove(key);
            configMap.remove(key);
        }else{
            //对配置表进行了读取、添加、更新  应该从读取的信息更新到状态以及ConfigMap
            broadcastState.put(key,tp);
            configMap.put(key,tp);
        }
    }
}
